#include <iostream>
#include <string>
#include <assert.h>
#include <cstdio>
#include <cstring>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
using namespace std;

void hander(int sig)
{
    sleep(1);
    cout << "kill signal:" << sig << endl;
}

int main()
{
    signal(SIGPIPE, hander);//对于管道产生的异常信号更改，并且没有处理异常，所以会循环

    // 创建管道
    int pipefd[2] = {0};
    int ret = pipe(pipefd);
    assert(ret == 0);
    (void)ret;
    // 创建子进程

    pid_t id = fork();
    if (id == 0)
    {
        // 子进程

        close(pipefd[0]);
        string str = "我是子进程，我正在和你通讯";
        int count = 0;
        char buffer_end[1024];

        while (true)
        {
            snprintf(buffer_end, sizeof(buffer_end), "%s[%d]", str.c_str(), count);
            count++;
            size_t len = strlen(buffer_end);
            // cout << len << endl;
            write(pipefd[1], buffer_end, len);
            sleep(1);
        }

        exit(0);
    }
    // 父进程

    close(pipefd[1]);
    char buffer[1024];
    int count = 5;
    while (count--)
    {
        ssize_t sz = read(pipefd[0], buffer, sizeof(buffer) - 1);
        if (sz > 0)
        {
            buffer[sz] = 0;
            cout << "father#" << buffer << endl;
        }
    }
    close(pipefd[0]);
    int status = 0;
    pid_t pid = waitpid(id, &status, 0);
    assert(pid != -1);
    if(WIFEXITED(status))
        cout << "退出码为：" << WEXITSTATUS(status) << endl;
    else if(WIFSIGNALED(status))
        cout << "终止信号：" << WTERMSIG(status) << endl;
    (void)pid;
    // 关闭对应的fd
    // 子进程读数据父进程写数据
    // 关闭文件，父进程等待子进程退出

    return 0;
}